package com.masterlu.leetcode.daily.linkedlist.medium;

import com.masterlu.leetcode.daily.linkedlist.ListNode;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 *
 * @Author：masterlu
 * @Date：2021/4/2 9:19 上午
 */
public class M2TwoNumberSum {

    /**
     * [2,4,3]
     * [5,6,4]
     *
     */

    public static void main(String[] args) {
        ListNode l1 = new ListNode(9);
        l1.next = new ListNode(9);
        l1.next.next = new ListNode(9);
        l1.next.next.next = new ListNode(9);
        l1.next.next.next.next = new ListNode(9);

        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9);

        addTwoNumbers(l1, l2);

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        //标示数字相加时，是否需要进位。默认不进位
        int flag = 0;
        ListNode sumListHead = new ListNode();
        ListNode curr = sumListHead.next;
        while (l1 != null || l2 != null) {
            ListNode sumNode = new ListNode();

            int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + flag;
            sumNode.val = sum % 10;
            flag = sum / 10;


            if (null != l1) {
                l1 = l1.next;
            }
            if (null != l2) {
                l2 = l2.next;
            }

            if (curr == null) {
                sumListHead = sumNode;
                curr = sumNode;
            } else {
                curr.next = sumNode;
                curr = sumNode;
            }

        }

        //TODO 实现过程中，忘记最后1的保存
        if (flag == 1){
            curr.next = new ListNode(1);
        }

        return sumListHead;
    }

}